<template>
  <div class="app-container">
    <el-card class="box-card" shadow="hover">
      <div slot="header" class="clearfix">
        <span class="card-title">部门管理</span>
      </div>
      
      <div class="filter-container">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索部门名称/描述"
          class="filter-item search-input"
          clearable
          prefix-icon="el-icon-search"
          @keyup.enter.native="handleSearch"
          @clear="handleSearch"
        />
        <el-button type="primary" icon="el-icon-search" class="filter-item" @click="handleSearch">搜索</el-button>
        
        <div class="action-buttons">
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加部门</el-button>
          <el-button type="danger" icon="el-icon-delete" :disabled="selection.length === 0" @click="handleBatchDelete">批量删除</el-button>
          <el-button type="warning" icon="el-icon-download" @click="handleExport">导出</el-button>
        </div>
      </div>
      
      <el-table
        v-loading="loading"
        :data="paginatedData"
        border
        stripe
        highlight-current-row
        @selection-change="handleSelectionChange"
        class="department-table"
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="name" label="部门名称" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-tag type="primary" size="medium">{{ scope.row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="部门描述" min-width="200" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip>
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="primary" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
            <el-button size="mini" type="success" icon="el-icon-user" @click="handleViewUsers(scope.row)">查看用户</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          background
          :current-page.sync="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredTableData.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 添加/编辑部门对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" @close="resetForm">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="部门描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入部门描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 查看部门用户对话框 -->
    <el-dialog title="部门用户" :visible.sync="userDialogVisible" width="900px">
      <div v-loading="userLoading">
        <div class="department-info">
          <el-tag type="success" effect="dark" size="medium">{{ currentDepartment ? currentDepartment.name : '' }}</el-tag>
          <span class="department-user-count">共 {{ departmentUsers.length }} 名用户</span>
        </div>
        
        <el-table :data="departmentUsers" border stripe class="user-list-table" style="width: 100%">
          <el-table-column prop="username" label="用户名" width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-tag size="medium">{{ scope.row.username }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="realName" label="真实姓名" width="120" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机号" width="120" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              {{ formatTime(scope.row.createTime) }}
            </template>
          </el-table-column>
        </el-table>
        
        <div class="dialog-footer" style="margin-top: 20px; text-align: right;">
          <el-button @click="userDialogVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getAllDepartments,
  getDepartmentWithUsersById,
  addDepartment,
  updateDepartment,
  deleteDepartment,
  batchDeleteDepartments,
  exportDepartments,
  searchDepartments
} from '@/api/department'
import { formatTime, handleDownload } from '@/utils'

export default {
  name: 'DepartmentList',
  data() {
    return {
      loading: false,
      userLoading: false,
      tableData: [],
      filteredTableData: [],
      selection: [],
      currentPage: 1,
      pageSize: 10,
      searchKeyword: '',
      dialogVisible: false,
      userDialogVisible: false,
      dialogTitle: '',
      form: {
        id: null,
        name: '',
        description: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      currentDepartment: null,
      departmentUsers: []
    }
  },
  computed: {
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.filteredTableData.slice(start, end)
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatTime,
    async fetchData() {
      this.loading = true
      try {
        const res = await getAllDepartments()
        if (res.code === 200) {
          this.tableData = res.data || []
          this.filteredTableData = [...this.tableData]
        }
      } catch (error) {
        console.error('获取部门列表失败', error)
        this.$message.error('获取部门列表失败')
      } finally {
        this.loading = false
      }
    },
    async handleSearch() {
      this.loading = true
      try {
        // 构建搜索参数
        const params = {}
        if (this.searchKeyword) {
          params.keyword = this.searchKeyword
        }
        
        // 如果没有搜索条件，使用之前获取的所有数据
        if (!params.keyword) {
          this.filteredTableData = [...this.tableData]
          this.currentPage = 1
          return
        }
        
        // 发送搜索请求到后端
        const res = await searchDepartments(params)
        if (res.code === 200) {
          this.filteredTableData = res.data || []
        } else {
          this.$message.error(res.message || '搜索失败')
        }
      } catch (error) {
        console.error('搜索部门失败', error)
        this.$message.error('搜索部门失败: ' + (error.message || '未知错误'))
      } finally {
        this.loading = false
        this.currentPage = 1
      }
    },
    handleSelectionChange(selection) {
      this.selection = selection
    },
    handleSizeChange(val) {
      this.pageSize = val
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    handleAdd() {
      this.dialogTitle = '添加部门'
      this.form = {
        id: null,
        name: '',
        description: ''
      }
      this.dialogVisible = true
    },
    async handleEdit(row) {
      this.dialogTitle = '编辑部门'
      this.form = {
        id: row.id,
        name: row.name,
        description: row.description
      }
      this.dialogVisible = true
    },
    async handleDelete(row) {
      this.$confirm('确认删除该部门?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const res = await deleteDepartment(row.id)
          if (res.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          }
        } catch (error) {
          console.error('删除部门失败', error)
          this.$message.error('删除部门失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {})
    },
    async handleBatchDelete() {
      if (this.selection.length === 0) {
        this.$message.warning('请选择要删除的部门')
        return
      }
      
      this.$confirm(`确认删除选中的 ${this.selection.length} 个部门?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const ids = this.selection.map(item => item.id)
          const res = await batchDeleteDepartments(ids)
          if (res.code === 200) {
            this.$message.success('批量删除成功')
            this.fetchData()
          }
        } catch (error) {
          console.error('批量删除部门失败', error)
          this.$message.error('批量删除部门失败')
        } finally {
          this.loading = false
        }
      }).catch(() => {})
    },
    async handleExport() {
      this.loading = true
      try {
        const res = await exportDepartments()
        handleDownload(res, '部门列表.xlsx')
        this.$message.success('导出成功')
      } catch (error) {
        console.error('导出部门失败', error)
        this.$message.error('导出部门失败')
      } finally {
        this.loading = false
      }
    },
    async handleViewUsers(row) {
      this.userDialogVisible = true
      this.currentDepartment = row
      this.userLoading = true
      this.departmentUsers = []
      
      try {
        const res = await getDepartmentWithUsersById(row.id)
        if (res.code === 200 && res.data) {
          this.departmentUsers = res.data.users || []
        }
      } catch (error) {
        console.error('获取部门用户失败', error)
        this.$message.error('获取部门用户失败')
      } finally {
        this.userLoading = false
      }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.loading = true
          const isEdit = this.form.id !== null
          try {
            const res = isEdit
              ? await updateDepartment(this.form.id, this.form)
              : await addDepartment(this.form)
            
            if (res.code === 200) {
              this.$message.success(isEdit ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            }
          } catch (error) {
            console.error(isEdit ? '更新部门失败' : '添加部门失败', error)
            this.$message.error(isEdit ? '更新部门失败' : '添加部门失败')
          } finally {
            this.loading = false
          }
        }
      })
    },
    resetForm() {
      this.$refs.form && this.$refs.form.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .card-title {
    font-size: 18px;
    font-weight: bold;
    color: #303133;
  }
  
  .filter-container {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
      margin-bottom: 10px;
    }
    
    .search-input {
      width: 300px;
    }
    
    .action-buttons {
      margin-left: auto;
      display: flex;
      gap: 10px;
      flex-wrap: wrap;
    }
  }
  
  .department-table {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
  
  .department-info {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    
    .department-user-count {
      margin-left: 15px;
      color: #606266;
      font-size: 14px;
    }
  }
  
  .user-list-table {
    margin-top: 15px;
  }
}
</style> 